package com.rt.gptnext.common.utils.http;

import cn.hutool.core.io.IoUtil;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;

/**
 * http响应流
 *
 * @author gaoyiyang
 */
public interface HttpStream {

    /**
     * 读取字符串
     *
     * @return 字符串
     */
    String readStr();

    /**
     * 读取一行
     *
     * @return 读取一行
     */
    String readLine();

    /**
     * 读取
     *
     * @param function 读取函数
     * @param readLine 是否读取一行
     */
    default void read(Function<String, Boolean> function, boolean readLine) {
        String line;
        while ((line = readLine ? readLine() : readStr()) != null) {
            var res = function.apply(line);
            if (Boolean.FALSE.equals(res)) {
                return;
            }
        }
    }

    /**
     * 读取
     *
     * @param function 读取函数
     */
    default void read(Function<String, Boolean> function) {
        read(function, false);
    }

    /**
     * 写入到输出流
     *
     * @param out      输出流
     * @param readLine 是否读取一行
     */
    default void writeTo(OutputStream out, boolean readLine) {
        String line;
        while ((line = readLine ? readLine() : readStr()) != null) {
            IoUtil.write(out, StandardCharsets.UTF_8, false, line);
        }
    }

    /**
     * 写入
     *
     * @param out 输出流
     */
    default void writeTo(OutputStream out) {
        writeTo(out, false);
    }

}
